#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2020/8/20 14:23
# @Author : LZQ
# @Version：V 0.1
# @File : reports.py
# @desc :
from . import api, report
from app.token_verify import verify
from flask import request, current_app, g, jsonify
from sqlalchemy import and_, or_, desc
from app.models import Report_1, Report_2, Report_3
from __init__ import redis_store, db
import json


@report.route("/type/<int:type_id>", methods=["GET"])
@verify
def get_user_report(type_id):
    data = []
    legend = {"data": []}
    yAxis = [{
        "type_id": "value"
    }]
    user_count = []
    xAxis = [{"data": data}]
    series = []
    res = {}
    try:
        if type_id == 1:
            reports_1 = Report_1.query.filter().all()
            count = 0
            report_2 = Report_1.query.filter().order_by(Report_1.rp1_area).all()
            series_inner_dict = {}
            index = 0
            for report in report_2:
                if index == 0:
                    series_inner_dict[report.rp1_area] = []
                if index < len(report_2) - 1:
                    index += 1
                series_inner_dict[report.rp1_area].append(report.rp1_user_count)
                if report.rp1_area != report_2[index].rp1_area:
                    series_inner_dict[report_2[index].rp1_area] = []
                    # print("当前key：%s   下一次的key:%s", (report.rp1_area, report_2[index].rp1_area))
            for report_1 in reports_1:
                count += 1

                if count % 5 == 0:
                    data.append(report_1.date_to_string())
                if report_1.rp1_area not in legend['data']:
                    legend['data'].append(report_1.rp1_area)
                    dict = {"name": report_1.rp1_area, "type": "line", "stack": "总量", "areaStyle": {"normal": {}},
                            "data": series_inner_dict[report_1.rp1_area]}
                    series.append(dict)
        elif type_id == 2:
            reports_2 = Report_2.query.filter().all()
            for report_2 in reports_2:
                data.append(report_2.to_dict())
        else:
            reports_3 = Report_3.query.filter().all()
            for report_3 in reports_3:
                data.append(report_3.to_dict())
        data_dict = {"data": {"legend": legend, "yAxis": yAxis, "xAxis": xAxis, "series": series},
                     "meta": {"code": 200, "msg": "获取折线图数据成功"}}
    except Exception as e:
        current_app.logger.error(e)
        data_dict = {"code": 400, "msg": "数据库错误"}
    return jsonify(data_dict)
